package com.william.lifetraxer;

import static com.william.lifetraxer.util.DbManager.*;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.william.lifetraxer.util.User;
import com.william.lifetraxer.util.UserDAO;

import static com.william.lifetraxer.util.Values.*;

public class UserHandler extends HttpServlet {

	public UserHandler() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String handleType = request.getParameter("user_handle_type");
		String username = request.getParameter("user_username");
		String password = request.getParameter("user_password");
		String newPassword = request.getParameter("user_new_password");
		
		if("insert_user".equals(handleType))
		{
			int userid = UserDAO.insertUser(new User(username,password));
			if(userid==DATABASE_ERROR)
			{
				out.print("DATABASE_ERROR");
			}
			else if(userid==USER_EXIST)
			{
				out.print("USER_EXIST");
			}
			else
			{
				out.print(userid);
			}
		}
		else if("reset_password".equals(handleType)&&newPassword!=null)
		{
			int result = UserDAO.resetPassword(new User(username,password), newPassword);
			if(result==RESET_PASSWORD_OK)
			{
				out.print("RESET_PASSWORD_OK");
			}
			else if(result==PASSWORD_ERROR)
			{
				out.print("PASSWORD_ERROR");
			}
			else if(result==DATABASE_ERROR)
			{
				out.print("DATABASE_ERROR");
			}
		}
		else
		{
			out.print("VALID_USER_HANDLE_TYPE");
		}
		out.close();
	}

}
